package com.zhugang.week07;

/**
 * @program algorithms
 * @description: treeToDoublyList
 * @author: chanzhugang
 * @create: 2022/08/03 10:26
 */
public class TreeToDoublyList2 {

    /**
     * 剑指offer 36 二叉搜索树与双向循环链表
     *
     * @param root
     * @return
     */
    Node newHead = new Node();
    Node tail = newHead;

    public Node treeToDoublyList(Node root) {
        if (root == null) {
            return null;
        }
        // 排序的双向循环链表：中序遍历，前驱指针 、后继指针
        inorder(root);
        // 处理首尾连接
        tail.right = newHead.right;
        newHead.right.left = tail;
        return newHead.right;
    }

    private void inorder(Node root) {
        if (root == null) {
            return;
        }
        inorder(root.left);
        // 中序处理逻辑，循环链表, tail -> root (画图理解)
        root.left = tail;
        tail.right = root;
        tail = root;

        inorder(root.right);
    }

    class Node {
        public int val;
        public Node left;
        public Node right;

        public Node() {
        }

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, Node _left, Node _right) {
            val = _val;
            left = _left;
            right = _right;
        }
    }


}